import 'package:dio/dio.dart';
import 'http_config.dart';

class HttpRequest {
  // 1.创建实例对象
  static BaseOptions baseOptions = BaseOptions(
      baseUrl: HttpConfig.baseUrl, connectTimeout: HttpConfig.connectTimeout);
  static Dio dio = Dio(baseOptions);

  static Future<T?> request<T>(String url,
      {String method = 'GET',
      Map<String, dynamic>? queryParameters,
      data,
      Map<String, dynamic>? headers,
      Interceptor? interceptor}) async {
    Options options = Options(method: method, headers: headers);

    Interceptor dInter = InterceptorsWrapper(
      // 请求拦截
      onRequest: (RequestOptions options, RequestInterceptorHandler handler) {
        var token = '';
        options.headers['Authorization'] = 'Basic $token';
        return handler.next(options); // 继续请求
      },
      // 响应拦截
      onResponse: (Response response, ResponseInterceptorHandler handler) {
        return handler.next(response);
      },
      // 错误拦截
      onError: (DioException err, ErrorInterceptorHandler handler) {
        print('错误拦截$err');
        return handler.next(err);
      },
    );
    List<Interceptor> inters = [dInter];

    // 请求单独拦截器
    if (interceptor != null) {
      inters.add(interceptor);
    }
    // 统一添加到拦截器中
    dio.interceptors.addAll(inters);
    // 发送网络请求
    try {
      Response response = await dio.request(url,
          queryParameters: queryParameters, data: data, options: options);
      return response.data;
    } catch (e) {
      return Future.error(e);
    }
  }
}
